package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.view.View
import android.widget.DatePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.CarBrandParam
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.bean.KeyValueParam
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.SearchResultActivity
import com.cheyun.netsalev3.view.choosecar.ChooseCarActivity
import com.cheyun.netsalev3.view.mars.choosecar.MarsChooseCarActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyDialog
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap


/**
 * @author Michael
 * @date  2018/11/7 - 15:06.
 */
class AdvancedSearchActivityViewModel(var nkey: String) : BaseViewModel() {
    var listItem = MutableLiveData<List<KeyValueParam>>()
    //一级
//    var typeShow1 = ObservableField<KeyValueParam>()
    var typeShow1 = MutableLiveData<KeyValueParam>()
    var position1 = -1
    //二级
//    var typeShow2 = ObservableField<MyDialog.DialogParam>(MyDialog.DialogParam("", ""))
    var typeShow2 = MutableLiveData<DialogParam>()
    var position2 = -1
    private var infotype: Array<KeyValueParam>

    init {

        var baseData = MySharedPreferences.getBaseData()
        //业务类型
        var infotypelist = ArrayList<DialogParam>()
        baseData?.infotype?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                infotypelist.add(item)
            }
        }
        //信息渠道
        var infoplacelist = ArrayList<DialogParam>()
        baseData?.infoplace?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                infoplacelist.add(item)
            }
        }
        //信息来源
        var infosourcelist = ArrayList<DialogParam>()
        baseData?.infosource?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                infosourcelist.add(item)
            }
        }

        //有效性判断
        var effectivelist = ArrayList<DialogParam>()
        baseData?.effective?.apply {
//            var item0 = DialogParam(this.key0, "0")
//            effectivelist.add(item0)
//            var item1 = DialogParam(this.key1, "1")
//            effectivelist.add(item1)
//            var item2 = DialogParam(this.key2, "2")
//            effectivelist.add(item2)
        }
        //拟上本地车牌
        var licenceplatelist = arrayListOf(
                DialogParam("是", "1"),
                DialogParam("否", "0")
        )

        //信息来源
        var owneruidlist = ArrayList<DialogParam>()
        baseData?.member?.apply {
            for (i in this) {
                var item = DialogParam(i.realname, i.uid.toString())
                owneruidlist.add(item)
            }
        }
//        //拟购时间
//        var ibuytimelist = ArrayList<DialogParam>()
//        baseData?.ibuytime?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                ibuytimelist.add(item)
//            }
//        }
        //跟进级别
        var customerlevellist = ArrayList<DialogParam>()
        baseData?.customerlevel?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                customerlevellist.add(item)
            }
        }
        //跟进报警
        var followalarmlist = ArrayList<DialogParam>()
        baseData?.followalarm?.apply {
            for (index in 0 until this.size){
                var item = DialogParam(this.get(index).toString(),index.toString() )
                followalarmlist.add(item)
            }
//            for (i in this) {
//                var item = DialogParam(i, i.toString())
//                followalarmlist.add(item)
//            }
        }
        //跟进/回访方式
        var connectwaylist = ArrayList<DialogParam>()
        baseData?.connectway?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                connectwaylist.add(item)
            }
        }
        //拟购车辆颜色
        var exteriorlist = ArrayList<DialogParam>()
        baseData?.exterior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                exteriorlist.add(item)
            }
        }
        //拟购内饰颜色
        var interiorlist = ArrayList<DialogParam>()
        baseData?.interior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                interiorlist.add(item)
            }
        }
        //客户类型
        var customertypelist = arrayListOf(
                DialogParam("个人", "1"),
                DialogParam("公司", "2"),
                DialogParam("行政单位", "3")
        )
        //购买类型
        var purchasetypelist = arrayListOf(
                DialogParam("首购", "1"),
                DialogParam("增购", "2"),
                DialogParam("置换", "3")
        )
        //保险公司
//        var insurerlist = ArrayList<DialogParam>()
//        baseData?.insurer?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                insurerlist.add(item)
//            }
//        }
        //支付方式
        var paymentwaylist = ArrayList<DialogParam>()
        baseData?.paymentway?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                paymentwaylist.add(item)
            }
        }
        //按揭银行
        var banklist = ArrayList<DialogParam>()
        baseData?.bank?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                banklist.add(item)
            }
        }
        //会员
//        var mlevellist = ArrayList<DialogParam>()
//        baseData?.mlevel?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                mlevellist.add(item)
//            }
//        }
        //无效原因
        var invalidlist = ArrayList<DialogParam>()
        baseData?.invalid?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                invalidlist.add(item)
            }
        }
        //线索标签
        var tracktaglist = ArrayList<DialogParam>()
        baseData?.ntags?.apply {
            for (i in this) {
                var item = DialogParam(i.title + "(线上)", i.id.toString())
                tracktaglist.add(item)
            }
        }
        baseData?.mtags?.apply {
            for (i in this) {
                var item = DialogParam(i.title+ "(线下)", i.id.toString())
                tracktaglist.add(item)
            }
        }
        //7日强转
        var archivemovelist = arrayListOf(
                DialogParam("未到店将强制转出", "1"),
                DialogParam("未成交将强制转出", "2")
        )

        infotype = arrayOf(
                //type2输入框类型 1选择类型框
                KeyValueParam("客户姓名", 2, "uname"),
                KeyValueParam("客户电话", 2, "phone"),
                KeyValueParam("意向车系",1, "series"),
                KeyValueParam("线索类型", infotypelist, "infotype"),
                KeyValueParam("触点渠道", infoplacelist, "infoplace"),
                KeyValueParam("信息来源", infosourcelist, "infosource"),
                KeyValueParam("有效性判断", effectivelist, "effective"),
                KeyValueParam("拟上本地车牌", licenceplatelist, "licenceplate"),
                KeyValueParam("线索拥有者", owneruidlist, "owneruid"),
//                KeyValueParam("拟购时间", ibuytimelist, "ibuytime"),
                KeyValueParam("跟进级别", customerlevellist, "customerlevel"),
                KeyValueParam("跟进报警", followalarmlist, "followalarm"),
                KeyValueParam("跟进/回访方式", connectwaylist, "ncway"),
                KeyValueParam("是否到店", licenceplatelist, "arrive"),
                KeyValueParam("是否试驾", licenceplatelist, "driving"),
                KeyValueParam("意向车辆颜色", exteriorlist, "exterior"),
                KeyValueParam("意向内饰颜色", interiorlist, "interior"),
                KeyValueParam("客户类型", customertypelist, "customertype"),
                KeyValueParam("购买类型", purchasetypelist, "purchasetype"),
                KeyValueParam("现用品牌",1, "pbrand"),
                KeyValueParam("订车车系",1, "iseries"),
                KeyValueParam("订车车辆颜色", exteriorlist, "strikeexterior"),
                KeyValueParam("提车车系",1, "dseries"),
                KeyValueParam("提车车辆颜色", exteriorlist, "deliverexterior"),
                KeyValueParam("提车内饰颜色", interiorlist, "deliverinterior"),
                KeyValueParam("订单号", 2, "ordernum"),
                KeyValueParam("车牌号", 2, "plate"),
                KeyValueParam("车架号", 2, "vin"),
//                KeyValueParam("保险公司", insurerlist, "insurer"),
                KeyValueParam("微信账号", 2, "weixin"),
                KeyValueParam("保单号", 2, "policyno"),
                KeyValueParam("支付方式", paymentwaylist, "paymentway"),
                KeyValueParam("按揭银行", banklist, "loanbank"),
//                KeyValueParam("会员", mlevellist, "mlevel"),
                KeyValueParam("线索无效原因", invalidlist, "invalid"),
                KeyValueParam("线索标签", tracktaglist, "tracktag"),
                KeyValueParam("7日强转", archivemovelist, "archivemove")
        )

    }

    /**
     * 选中类型1
     */
    fun onClickType(view: View) {
        var content = view.context

        if (content is AppCompatActivity) {
            //深拷贝
            var list = ArrayList<DialogParam>()
            for (it in infotype) {
                var item = DialogParam(it.key, it.idname)
                item.IsSelect = it.IsSelect
                item.ikey = it.ikey
                list.add(item)
            }
            val newFragment = MyDialog.newInstance("请选择类型", list)
            newFragment.huidiaPosition = this::myPopSetData
            newFragment.show(content.supportFragmentManager, "missiles")
        }
    }

    /**
     * 选中类型回调1
     */
    fun myPopSetData(position: Int) {
        position1 = position
        position2 = -1
        if (position == -1) {
            return
        }

        for (i in 0 until infotype.size) {
            infotype[position].IsSelect = i == position
        }

//        typeShow1.set(infotype[position])
//        typeShow2.set(DialogParam("", ""))
        typeShow1.postValue(infotype[position])
        typeShow2.postValue(DialogParam("", ""))
    }

    /**
     * 选中类型2
     */
    fun onClickType2(view: View) {
        var content = view.context

        if (content is AppCompatActivity) {
            //深拷贝
            var list = ArrayList<DialogParam>()
            var poptitle = ""
            if (position1 != -1) {
                if(infotype[position1].idname.equals("series")){
                    //拟购车系
                    onClicCar(view,1)
                    return;
                }
                if(infotype[position1].idname.equals("pbrand")){
                    //现用品牌
                    onClicCar2(view,0);
                    return;
                }
                if(infotype[position1].idname.equals("iseries")){
                    //订车车系
                    onClicCar3(view,0,103);
                    return;
                }
                if(infotype[position1].idname.equals("dseries")){
                    //提车车系
                    onClicCar3(view,0,104);
                    return;
                }
                var poplistdata = infotype[position1].poplistdata
                for (it in poplistdata) {
                    var item = DialogParam(it.name, it.id)
                    item.IsSelect = it.IsSelect
                    item.ikey = it.ikey
                    list.add(item)
                }
                poptitle = infotype[position1].poptitle
            }

            val newFragment = MyDialog.newInstance("请选择$poptitle", list)
            newFragment.huidiaPosition = this::myPopSetData2
            newFragment.show(content.supportFragmentManager, "missiles2")
        }
    }

    /**
     * 点击 品牌=0 车系=1车型=2
     */
    fun onClicCar(view: View, p: Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, MarsChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            intent.putExtra("Isseries",true)
            var car = CarBrandParam();
            intent.putExtra("car", car as Serializable)
            content.startActivityForResult(intent, 101)
        }
    }

    /**
     * 点击 现有品牌=0 车系=1
     */
    fun onClicCar2(view: View, p: Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, ChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            intent.putExtra("Isbrand",true)
            var car = CarBrandParam()
            intent.putExtra("car", car as Serializable)
            content.startActivityForResult(intent, 102)
        }
    }
//
    /**
     * 订车车系
     */
    fun onClicCar3(view: View, p: Int,type:Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, MarsChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            intent.putExtra("Isseries",true)
            var car = CarBrandParam()
            intent.putExtra("car", car as Serializable)
            content.startActivityForResult(intent, type)
        }
    }



    fun setCarData(carBrandParam: CarBrandParam) {
//        typeShow2.set(DialogParam(carBrandParam.seriesname, carBrandParam.series))
        typeShow2.postValue(DialogParam(carBrandParam.seriesname, carBrandParam.series))
    }
    fun setCarData2(carBrandParam: CarBrandParam) {
//        typeShow2.set(DialogParam(carBrandParam.brandname, carBrandParam.brand))
        typeShow2.postValue(DialogParam(carBrandParam.brandname, carBrandParam.brand))
    }

    /**
     * 选中类型回调2
     */
    fun myPopSetData2(position: Int) {
        position2 = position
        if (position == -1) {
            return
        }

        var list = infotype[position1].poplistdata

        for (i in 0 until list.size) {
            list[position].IsSelect = i == position
        }
//        typeShow2.set(list[position])
        typeShow2.postValue(list[position])
    }

    /**
     * 添加item
     */
    fun addItem(view: View) {
//        var type1 = typeShow1.get()
//        var type2 = typeShow2.get()
        if(typeShow1?.value == null)return;
        if(typeShow2?.value == null)return;
        var type1 = typeShow1.value!!
        var type2 = typeShow2.value!!
        var list = HashSet<KeyValueParam>()
        var hasSameItem:Boolean = false
        listItem.value?.apply {
            for(i in 0 until  this.size){
                if(this.get(i).idname.equals(type1?.idname)){
                    hasSameItem = true
                    var item = this.get(i)
                    type2?.apply {
                        if (this.name == "") {
                            return
                        }
                        if (id == ""){
                            item.key = this.name
                            item.value = this.name
                        }
                        else {
                            item.key = this.name
                            item.value = this.id
                        }
                    }
                }
            }
        }
        if(!hasSameItem){
            listItem.value?.apply {
                list.addAll(this)
            }
            if (list.size >= 5) {
                MyToast( "最多只能增加5个条件")
                return
            }

            type1?.apply {
                var idname = this.idname
                type2?.apply {
                    if (this.name == "") {
                        return
                    }
                    var item = if (id == "") KeyValueParam(this.name, this.name)
                    else KeyValueParam(this.name, this.id)
                    item.idname = idname
                    list.add(item)
                    listItem.postValue(list.toList())
                }
            }
        }
    }

    /**
     * 删除item
     */
    fun onClickDel(view: View, item: KeyValueParam, position: Int) {

        var list = HashSet<KeyValueParam>()
        listItem.value?.apply {
            list.addAll(this)
            list.remove(item)
        }
        listItem.postValue(list.toList())
    }

    /**
     * 开始时间
     */
    fun startTime(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onDateSetstart
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }

    var year1 = -1
    var month1 = -1
    var day1 = -1

    var year2 = -1
    var month2 = -1
    var day2 = -1
    var showStartT = ObservableField<String>("")
    var showStartE = ObservableField<String>("")
    /**
     * 开始时间回调
     */
    fun onDateSetstart(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year1 = year
        this.month1 = month
        this.day1 = day
        showStartT.set("$year1-$month1-$day1")
    }

    /**
     * 结束时间回调
     */
    fun onDateSetend(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year2 = year
        this.month2 = month
        this.day2 = day
        showStartE.set("$year2-$month2-$day2")
    }

    /**
     * 结束时间
     */
    fun endTime(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onDateSetend
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }

    /**
     * 搜索
     */
    fun searchBut(view: View) {
        var hashMap = HashMap<String, String>()
        listItem.value?.apply {
            for (i in this) {
                hashMap[i.idname] = i.value
            }
        }
        showDatetype.get()?.apply {
            hashMap["datetype"] = this.id
            showStartT.get()?.apply {
                hashMap["stime"] = this
            }
            showStartE.get()?.apply {
                hashMap["etime"] = this
            }
        }


        var intent = Intent(view.context, SearchResultActivity::class.java)
        intent.putExtra("nkey", nkey)
        intent.putExtra("hashMap", hashMap)
        view.context.startActivity(intent)
    }

    var datetypelist = arrayListOf(
            DialogParam("提交时间", "posttime"),
            DialogParam("邀约到店时间", "invitetime"),
            DialogParam("首次到店时间", "firstarrivetime"),
            DialogParam("下次跟进时间", "remindetime"),
            DialogParam("最后跟进回访时间", "followtime"),
            DialogParam("线索创建时间", "dateline"),
            DialogParam("客户到店时间", "arrivetime"),
            DialogParam("预订成交时间", "endtime"),
            DialogParam("提车时间", "delivertime")

    )

    var showDatetype = ObservableField<DialogParam>()
    /**
     * 点击时间类型
     */
    fun onClickDatetype(view: View) {
        var content = view.context

        if (content is AppCompatActivity) {
            //深拷贝
            var list = ArrayList<DialogParam>()
            for (it in datetypelist) {
                var item = DialogParam(it.name, it.id)
                item.IsSelect = it.IsSelect
                item.ikey = it.ikey
                list.add(item)
            }

            val newFragment = MyDialog.newInstance("请选择时间类型", list)
            newFragment.huidiaPosition = this::myPopSetDataTime
            newFragment.show(content.supportFragmentManager, "myPopSetDataTime")
        }
    }

    /**
     * 选中s时间类型回调
     */
    fun myPopSetDataTime(position: Int) {
        if (position == -1) {
            return
        }

        for (i in 0 until datetypelist.size) {
            datetypelist[position].IsSelect = i == position
        }
        showDatetype.set(datetypelist[position])
        showStartE.set("")
        showStartT.set("")

    }

}